const { app } = require('electron')
const path = require('path')
const fs = require('fs')

// 添加日志工具
const logger = {
  log: function (...args) {
    const time = new Date().toLocaleString()
    console.log(`[${time}]`, ...args)
  },
  error: function (...args) {
    const time = new Date().toLocaleString()
    console.error(`[${time}] [错误]`, ...args)
  },
  warn: function (...args) {
    const time = new Date().toLocaleString()
    console.warn(`[${time}] [警告]`, ...args)
  },
  info: function (...args) {
    const time = new Date().toLocaleString()
    console.info(`[${time}] [信息]`, ...args)
  }
}

// 添加文件日志功能
function setupFileLogging() {
  const logDir = path.join(app.getPath('userData'), 'logs')
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true })
  }

  const logFile = path.join(logDir, `app-${new Date().toISOString().split('T')[0]}.log`)
  const logStream = fs.createWriteStream(logFile, { flags: 'a' })

  // 重定向 console 输出到文件
  const originalConsole = {
    log: console.log,
    error: console.error,
    warn: console.warn,
    info: console.info
  }

  console.log = function (...args) {
    const time = new Date().toLocaleString()
    const message = `[${time}] ${args.join(' ')}\n`
    logStream.write(message)
    originalConsole.log.apply(console, args)
  }

  console.error = function (...args) {
    const time = new Date().toLocaleString()
    const message = `[${time}] [错误] ${args.join(' ')}\n`
    logStream.write(message)
    originalConsole.error.apply(console, args)
  }

  console.warn = function (...args) {
    const time = new Date().toLocaleString()
    const message = `[${time}] [警告] ${args.join(' ')}\n`
    logStream.write(message)
    originalConsole.warn.apply(console, args)
  }

  console.info = function (...args) {
    const time = new Date().toLocaleString()
    const message = `[${time}] [信息] ${args.join(' ')}\n`
    logStream.write(message)
    originalConsole.info.apply(console, args)
  }

  // 处理未捕获的异常
  process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error)
  })

  // 处理未处理的 Promise 拒绝
  process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的 Promise 拒绝:', reason)
  })

  return logStream
}

module.exports = {
  logger,
  setupFileLogging
}